from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from random import randint

from meiduo_mall.libs.yuntongxun.sms import CCP


class SMSCodeView(APIView):

    def get(self, request, mobile):
        """短信验证码"""

        print(mobile)

        # 建立连接
        conn = get_redis_connection('verify')
        flag = conn.get('sms_flag_%s' % mobile)

        if flag:
            return Response({'message': '请求过于频繁'}, status=400)

        # 生成短信验证码
        sms_code = '%06d' % randint(0, 999999)

        # 保存到 redis 缓存
        conn.setex('sms_code_%s' % mobile, 300, sms_code)
        conn.setex('sms_flag_%s' % mobile, 30, 'flag')

        # 发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, 5], 1)

        # 返回结果
        return Response({'message': 'ok'})
